/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.dictionary.impl.item;

import com.je.common.base.DynaBean;
import com.je.common.base.constants.ConstantVars;
import com.je.common.base.constants.dd.DDType;
import com.je.common.base.entity.QueryInfo;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.service.rpc.SystemVariableRpcService;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.service.common.MetaBeanService;
import com.je.meta.service.MetaDictionaryItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: jecloud-meta
 * @author: LIULJ
 * @create: 2021-09-17 13:40
 * @description: 列表字典项服务实现
 */
@Service("metaListDictionaryItemService")
public class MetaListDictionaryItemServiceImpl implements MetaDictionaryItemService {
    
    @Autowired
    private MetaService metaService;
    @Autowired
    private SystemVariableRpcService systemVariableRpcService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private MetaBeanService metaBeanService;

    @Override
    public List<JSONTreeNode> getDdItems(DynaBean dictionary, Map<String, String> params, QueryInfo queryInfo, Boolean en) {
        if(dictionary == null){
            throw new PlatformException("获取字典为空！",PlatformExceptionEnum.UNKOWN_ERROR);
        }
        //非列表字典抛出异常
        if(!DDType.LIST.equals(dictionary.getStr("DICTIONARY_DDTYPE"))){
            throw new PlatformException("获取字典项异常，非法的字典类型" + dictionary.getStr("DICTIONARY_DDTYPE"),PlatformExceptionEnum.UNKOWN_ERROR);
        }

        //声明变量集合，用于解析whereSql的通配符
        Map<String,Object> ddMap = systemVariableRpcService.formatCurrentUserAndCachedVariables();
        if (params != null && !params.isEmpty()) {
            ddMap.putAll(params);
        }

        //构建where
        String querySql = StringUtil.getDefaultValue(queryInfo.getWhereSql(), "");
        if (StringUtil.isNotEmpty(querySql)) {
            querySql = StringUtil.parseKeyWord(querySql, ddMap);
        }
        querySql = querySql + " and DICTIONARYITEM_DICTIONARY_ID='" + dictionary.getStr("JE_CORE_DICTIONARY_ID") + "' ";
        queryInfo.setWhereSql(querySql);

        //字典项元数据信息
        String tableName = "JE_CORE_DICTIONARYITEM";
        DynaBean table = metaBeanService.getResourceTable(tableName);
        List<DynaBean> columns = (List<DynaBean>) table.get(BeanService.KEY_TABLE_COLUMNS);

        String rootId = ConstantVars.TREE_ROOT;
        if (ConstantVars.TREE_ROOT.equals(rootId)) {
            DynaBean dynaBeanItem = metaService.selectOne("JE_CORE_DICTIONARYITEM",
                    ConditionsWrapper.builder().eq("DICTIONARYITEM_DICTIONARY_ID",dictionary.getStr("JE_CORE_DICTIONARY_ID"))
                            .eq("SY_NODETYPE","ROOT"));
            rootId = dynaBeanItem.getStr("JE_CORE_DICTIONARYITEM_ID");
        }

        JSONTreeNode template = metaBeanService.buildJSONTreeNodeTemplate(columns);
        if (en) {
            template.setText("DICTIONARYITEM_ITEMNAME_EN");
        }

        List<JSONTreeNode> lists = commonService.getLocalJsonTreeNodeList(rootId, tableName, template, queryInfo);
        List<DynaBean> items = metaService.select("JE_CORE_DICTIONARYITEM",ConditionsWrapper.builder().eq("DICTIONARYITEM_DICTIONARY_ID",dictionary.getStr("JE_CORE_DICTIONARY_ID")).apply(querySql));
        for (DynaBean item : items) {
            JSONTreeNode itemVo = new JSONTreeNode();
            itemVo.setId(item.getStr("JE_CORE_DICTIONARYITEM_ID"));
            itemVo.setText(item.getStr("DICTIONARYITEM_ITEMNAME"));
            if (en) {
                itemVo.setText(item.getStr("DICTIONARYITEM_ITEMNAME_EN"));
            }
            itemVo.setCode(item.getStr("DICTIONARYITEM_ITEMCODE"));
            itemVo.setNodeType(item.getStr("SY_NODETYPE"));
            itemVo.setNodeInfo(item.getStr("DICTIONARYITEM_NODEINFO"));
            itemVo.setNodeInfoType(item.getStr("DICTIONARYITEM_NODEINFOTYPE"));
            lists.add(itemVo);
        }
        return lists;
    }

}
